package com.ruoyi.web.service.zkService.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.web.domain.Dish;
import com.ruoyi.web.domain.DishFlavor;
import com.ruoyi.web.dto.DishDto;
import com.ruoyi.web.mapper.DishMapper;
import com.ruoyi.web.service.zkService.DishFlavorService;
import com.ruoyi.web.service.zkService.DishService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 菜品管理 服务实现类
 * </p>
 *
 * @author fancheng
 * @since 2022-11-05
 */
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;

    @Override
    /**
     * 新增菜品同时保存对应口味数据
     */
    @Transactional
    public void  saveWithFlavor(DishDto dishDto){
        //保存菜品到菜品表
        this.save(dishDto);

        Long id = dishDto.getId();//菜品id
        //口味列表中id未封装，需要手动封装
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor dish:flavors) {
            dish.setDishId(id);
        }
        dishFlavorService.saveBatch(flavors);
    }

    @Override
    /**
     * 根据id查询菜品信息和对应口味信息
     * @param id
     * @return
     */
    public DishDto getWithFlavor(Long id){
        //查询获得菜品信息
        Dish dish = this.getById(id);
        DishDto dishDto = new DishDto();
        //将菜品信息拷贝到dishDto对象中
        BeanUtils.copyProperties(dish,dishDto);
        //构造查询条件
        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DishFlavor::getDishId,dish.getId());
        //查询指定id的口味信息
        List<DishFlavor> list = dishFlavorService.list(wrapper);
        //将口味信息设置入dishdto中
        dishDto.setFlavors(list);

        return dishDto;
    }

    /**
     * 更新菜品信息与菜品口味
     * @param dishDto
     */
    public void updateWithFlavor(DishDto dishDto){
        this.updateById(dishDto);

        Long id = dishDto.getId();
        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(wrapper);

        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor dish : flavors) {
            dish.setDishId(dishDto.getId());

        }
        dishFlavorService.saveBatch(flavors);
    }
}
